package com.paipai.service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.paipai.client.ProductClient;
import com.paipai.client.UserClient;
import com.paipai.dao.PorderMapper;
import com.paipai.entity.Address;
import com.paipai.entity.Bidding;
import com.paipai.entity.Porder;
import com.paipai.entity.Product;
import com.paipai.myannotation.MyLog;
import com.paipai.utils.OrderCodeFactory;

@Transactional
@Service
public class PorderService implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
	@Autowired
	private PorderMapper porderMapper;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	// 商品远程调用
	@Autowired
	private ProductClient productClient;

	// 用户远程调用
	@Autowired
	private UserClient userClient;

	// MQ
	// @Autowired
	// private AmqpTemplate amqpTemplate;

	public PorderMapper getPorderMapper() {
		return porderMapper;
	}

	/**
	 * 查询订单
	 * 
	 * @param uid
	 * @return
	 */
	
	public HashMap<String, Object> findOrder(Integer pageNum, Integer pageSize, String accountType, int uid) {
		// 查询数据总量
		Integer count = porderMapper.findOrderByUid(accountType, uid);

		// 查询总页数
		Integer pageCount = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;

		// 分页工具 只对最后一条sql有效
		PageHelper.startPage(pageNum, pageSize);

		// 数据列表
		Example ex = new Example(Porder.class);
		Criteria crt = ex.createCriteria();
		if (!"".equals(uid)) {
			crt.andCondition(accountType, uid);
		}
		List<Porder> list = porderMapper.selectByExample(ex);

		// 新建map封装数据
		HashMap<String, Object> map = new HashMap<String, Object>();

		// 将总页数放入map
		map.put("pageCount", pageCount);
		// 数据总条数
		map.put("count", count);
		// 当前页
		map.put("pageNum", pageNum);
		// 每页数量
		map.put("pageSize", pageSize);
		// 当前数据量
		map.put("list", list);

		return map;

	}

	/**
	 * 支付订单
	 * 
	 * @param id
	 * @return
	 */
	
	public Integer paymentOrder(Integer id,String TradeNo) {

		Porder porder = new Porder();
		porder.setId(id);
		porder.setTradeNo(TradeNo);
		porder.setStatus("已付款");
		// 付款时间
		porder.setPaymentDate(new Date());
		return porderMapper.updateByPrimaryKeySelective(porder);
	}

	/**
	 * 取消订单
	 * 
	 * @param id
	 * @return
	 */
	public Integer cancelOrder(Integer id) {
		Porder porder = new Porder();
		porder.setId(id);
		porder.setStatus("取消");
		return porderMapper.updateByPrimaryKeySelective(porder);
	}

	/**
	 * 卖家发货
	 * 
	 * @param id
	 * @return
	 */
	public Integer deliverOrder(Integer id) {
		Porder porder = new Porder();
		porder.setId(id);
		porder.setStatus("已发货");
		// 发货时间
		porder.setDeliverDate(new Date());
		return porderMapper.updateByPrimaryKeySelective(porder);
	}

	/**
	 * 签收
	 * 
	 * @param id
	 * @return
	 */
	public Integer affirmSignOrder(Integer id) {
		Porder porder = new Porder();
		porder.setId(id);
		porder.setStatus("交易成功");
		// 发货时间
		return porderMapper.updateByPrimaryKeySelective(porder);
	}

	/**
	 * 检测拍卖到期时间
	 * 
	 * @param id
	 * @throws UnsupportedEncodingException
	 */
	
	public Boolean pollAuctionEndDate(Integer id) throws UnsupportedEncodingException {

		// 查询该商品在竞拍表有无竞拍信息
		Bidding bidding = productClient.findEndDatebiddingByProId(id);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		// 等于null就中止 ==无竞价信息 流拍
		if (bidding == null) {
			// 3表示流拍
			map.put("state", 3);
			// MQ 更新商品表
			sendMsg(map);
			return true;

		}
		System.out.println(bidding);
		// 如果不为null,成交 商品被拍下 生成订单 2表示成交
		map.put("state", 2);
		map.put("biduserId", bidding.getUserId());
		map.put("biduserName", bidding.getUserName());
		// MQ 更新商品表
		sendMsg(map);
		// 远程查询商品详情
		Product product = productClient.findProductEndDate(id);
		System.out.println(product);
		// 设置商品的得标人
		product.setBiduserId(bidding.getUserId());
		product.setBiduserName(bidding.getUserName());
		Porder order = new Porder();
		// 生成订单编号
		order.setOrderId(OrderCodeFactory.getRandom(5L));
		// 用户id 用户名
		order.setUserId(bidding.getUserId());
		order.setUserName(bidding.getUserName());
		// 商家id 用户名
		order.setSellerId(bidding.getSellerId());
		order.setSellerName(bidding.getSellerName());
		// 商品 id 序号 名称 图片 最终价格
		order.setProId(bidding.getProId());
		order.setProSerial(product.getSellerId());
		order.setProName(bidding.getProName());
		order.setProImg(bidding.getImg());
		order.setProPrice(bidding.getThisPrice());
		// 付款时间 订单状态
		order.setPlaceDate(new Date());
		order.setStatus("未付款");
		// 查询该用户的默认地址id
		Address address = userClient.findDefaultAddressByUserId(bidding.getUserId());
		// 如果查不到地址
		if (address == null) {
			System.out.println(product + "没有默认地址");
			order.setAddressId(null);
		} else {
			// 设置地址
			order.setAddressId(address.getId());
			order.setProvinces(address.getProvinces());
			order.setDetailedAddress(address.getDetailed());
			order.setRealName(address.getRealName());
			order.setPhone(address.getPhone());
			order.setPostalCode(address.getPostalCode());
		}

		// 插入订单
		int row = porderMapper.insert(order);
		System.out.println("商品被成功操作");
		return true;

	}

	/**
	 * 发送消息
	 *
	 * @param orderInfoModel
	 * @throws UnsupportedEncodingException
	 */
	public void sendMsg(HashMap<String, Object> map) throws UnsupportedEncodingException {
		// 消息体
		Message message = MessageBuilder.withBody(JSON.toJSONString(map).getBytes("UTF-8"))
				// 格式
				.setContentType(MessageProperties.CONTENT_TYPE_JSON)
				// 设置编码
				.setContentEncoding("UTF-8")
				// 设置message id
				.setMessageId(UUID.randomUUID().toString()).build();

		// 构建回调返回的数据
		CorrelationData correlationData = new CorrelationData(map.get("id").toString());

		// 检查是否成功发送到交换器
		this.rabbitTemplate.setMandatory(true);
		// 指定 ack
		this.rabbitTemplate.setConfirmCallback(this);
		// 发送消息
		rabbitTemplate.convertAndSend("paipai.productState.exchange", "paipai.state.product", message, correlationData);
	}

	@Override
	public void confirm(CorrelationData correlationData, boolean ack, String cause) {
		System.out.println("消息id:" + correlationData.getId()); // id 都是相同的哦 全局ID
		if (ack) { // 消息发送成功
			System.out.println("消息发送确认成功");
		} else {
			// 重试机制
			// sendMsg(orderId);
			System.out.println("消息发送确认失败:" + cause);
		}

	}

	@Override
	public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

		System.out.println("消息内容:{}" + new String(message.getBody()));
		System.out.println("回复文本:{},回复代码：{}" + replyText + replyCode);
		System.out.println("交换器名称:{},路由键：{}" + exchange + routingKey);

	}

	/**
	 * 以id查询订单信息
	 * 
	 * @param id
	 * @return
	 */
	public Porder findOrderById(Integer id) {
		Porder order = porderMapper.selectByPrimaryKey(id);
		return order;
	}

	/**
	 * 以自主生成id查询id信息
	 * 
	 * @param out_trade_no
	 * @return
	 */
	public Porder findOrderByOrderId(String out_trade_no) {
		if(out_trade_no==null) {
			return null;
		}
		Example example = new Example(Porder.class);

		Criteria crit = example.createCriteria();
		
		if(!"".equals(out_trade_no)) {
			crit.andCondition("order_id=",out_trade_no);
		}

		return porderMapper.selectOneByExample(example);
	}
	/**
	 * 退款
	 * @param id
	 * @return
	 */
	public Integer refundOrder(Integer id) {
		Porder porder = new Porder();
		porder.setId(id);
		porder.setStatus("已退款");
		// 发货时间
		return porderMapper.updateByPrimaryKeySelective(porder);
	}
	
	
	

}